$(function () {
    //1，将所用的变量都抽取出来，放在页面加载后
    var temporary_datagrid = $("#temporary_datagrid");
    var temporary_dialog = $("#temporary_dialog");
    var temporary_form = $("#temporary_form");
    var import_dialog = $("#import_dialog");

    var choose_customer_dialog = $("#choose_customer_dialog");

    //产品
    var choose1_product_dialog = $("#choose1_product_dialog");
    var product1_datagrid = $("#product1_datagrid");


    //客户
    var choose_potentialCustomer_dialog = $("#choose_potentialCustomer_dialog");
    var potentialCustomer_datagrid = $("#potentialCustomer_datagrid");


    //车辆
    var choose_car_dialog = $("#choose_car_dialog");
    var car_datagrid = $("#car_datagrid");

    //机构
    var safe_select = $("#safe_select");


    //产品
    var choose_product_dialog = $("#choose_product_dialog");
    var product_datagrid = $("#product_datagrid");

    //会员表格
    potentialCustomer_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        url:"/client/potentialCustomerList.do?status=1",
        pagination: true,
        singleSelect: true,
        rownumbers:true,
        columns: [[
            {field:'name',title:'客户姓名',width:70},
            {field:'gender',title:'性别',width:40,formatter:function (value, row, index) {
                if (value==null){
                    return '未知';
                }
                if (value){
                    return '男';
                }
                if (!value){
                    return '女';
                }
            }},
            {field:'tel',title:'电话',width:100},
            {field:'address',title:'客户地址',width:100},
            {field:'idNo',title:'身份证号',width:100}
        ]],
    })

    //车辆表格
    car_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        // toolbar: '#customer_toolbar',
        url:"/car/query.do",
        pagination: true,
        singleSelect: true,
        rownumbers:true,
        columns: [[
            {field: 'brand', title: '车辆品牌', width: 100},
            {field: 'model', title: '车辆型号', width: 100},
            {field: 'fasDisplacement', title: '排气量', width: 100},
            {field: 'valuation', title: '市场估价', width: 100},
            {field: 'category', title: '分类', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>载客</font>" : "<font color='red'>载物</font>"
                }
            },
            {field: 'size', title: '车载大小', width: 100,
                formatter: function (value, row, index) {
                    if (value==0&&value==''){
                        return "小型";
                    }else if (value==1){
                        return "中型";
                    }else if (value==1){
                        return "大型";
                    } else{
                        return "超大型";
                    }
                }
            },
            {field: 'remarks', title: '备注信息', width: 100}
        ]],
    })


    //机构
    safe_select.combogrid({
        url:'/organization/selectAll.do',
        panelWidth:450,
        value:'请选择',
        idField:'id',
        textField:'name',
        pagination: true,
        columns:[[
            {field: 'id', title: '编号', width: 50},
            {field: 'sn', title: '机构代码', width: 100},
            {field: 'name', title: '机构名称', width: 100},
            {field: 'legalPerson', title: '法人代表', width: 100},
            {field: 'identityInfo', title: '法人身份证', width: 100},
            {field: 'tel', title: '联系方式', width: 100},
            {field: 'address', title: '联系地址', width: 100},
            {field: 'cooperation', title: '合作状态', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>合作</font>" : "<font color='red'>解除</font>"
                }
            }
        ]],
        onChange:function () {
            var hiddens = $(".product-tr");
            $.each(hiddens, function (index, item) {
                if (index!=0){
                    $(item).remove();
                }
            });
            $("#totalAmount").html(0);
        },
        onClickRow:function (index, row) {
            $.get("/product/selectProductByOrganizationId.do",{id:row.id},function (data) {
                product_datagrid.datagrid("loadData", data);
            } );

        }
    })


    //产品
    product_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        toolbar: '#product_toolbar',
        url:"/product/query.do",
        pagination: true,
        rownumbers:true,
        ctrlSelect: true,
        columns: [[
            {field: 'sn', title: '保险编号', width: 100},
            {field: 'name', title: '保险名称', width: 100},
            {field: 'organizationId', title: '保险机构', width: 100,
                formatter: function (value, row, index) {
                    return value ? value.name : '';
                }},
            {field: 'organizationDate', title: '保障年限', width: 100},
            {field: 'imit', title: '保额', width: 100},
            {field: 'annuity', title: '基本年费', width: 100},
            {field: 'status', title: '销售状态', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>在售</font>" : "<font color='red'>停售</font>"
                }
            },
            {field: 'plan', title: '不计免赔', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>是</font>" : "<font color='red'>否</font>"
                }
            }
        ]]
    });


    choose1_product_dialog.dialog({
        width: 800,
        height: 350,
        closed: true,
        modal: true
    });

    //产品
    product1_datagrid.datagrid({
        fit: true,
        fitColumns: true,
        striped: true,
        toolbar: '#product_toolbar',
        url:"/temporary/selectByPrimaryKey.do",
        pagination: true,
        rownumbers:true,
        ctrlSelect: true,
        columns: [[
            {field: 'sn', title: '保险编号', width: 100},
            {field: 'name', title: '保险名称', width: 100},
            {field: 'organizationId', title: '保险机构', width: 100,
                formatter: function (value, row, index) {
                    return value ? value.name : '';
                }},
            {field: 'organizationDate', title: '保障年限', width: 100},
            {field: 'imit', title: '保额', width: 100},
            {field: 'annuity', title: '基本年费', width: 100},
            {field: 'status', title: '销售状态', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>在售</font>" : "<font color='red'>停售</font>"
                }
            },
            {field: 'plan', title: '不计免赔', width: 100,
                formatter: function (value, row, index) {
                    return value ? "<font color='blue'>是</font>" : "<font color='red'>否</font>"
                }
            }
        ]]
    });

    choose_potentialCustomer_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#potentialCustomer_btns2',
        closed: true,
        modal: true
    });
    choose_car_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#car_btns2',
        closed: true,
        modal: true
    });

    choose_product_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#product_btns2',
        closed: true,
        modal: true
    });

    temporary_datagrid.datagrid({
        url: '/temporary/queryTemporary.do',
        fitColumns: true,
        fit: true,
        pagination: true,    //分页条
        rownumbers: true,     //行号列
        singleSelect: true,
        sortName: 'hireDate',
        sortOrder: 'desc',
        toolbar: '#tb',
        columns: [[
            {field: 'sn', title: '保单编号', width: 100},
            {
                field: 'customer', title: '投保人', width: 100, formatter: function (value) {
                return value ? value.name : "";
            }
            },
            {field: 'applyDate', title: '申请日期', width: 100, sortable: true},
            {field: 'checkDate', title: '核保日期', width: 100, sortable: true},
            {field: 'endDate', title: '保险截止日', width: 100, sortable: true},
            {field: 'duration', title: '保险时长(/年)', width: 100},
            {
                field: 'inputUser', title: '业务员', width: 100, formatter: function (value) {
                return value ? value.username : "";
            }
            },
            {
                field: 'auditor', title: '审核人', width: 100, formatter: function (value) {
                return value ? value.username : "";
            }
            },
            {field: 'totalAmout', title: '投保总金额', width: 100, sortable: true},
            {field: 'state', title: '状态', width: 100,formatter: function (value) {
                var state="";
                if (value==0){
                    state="暂存待提交";
                } else if (value==1){
                    state ="未审核"
                } else if (value==2){
                    state ="退回修改"
                } else if (value==3){
                    state="<font color='red'>拒保</font>";
                } else if (value==4){
                    state ="已审核待缴费"
                } else if (value==5){
                    state ="已缴费"
                }
                return state;
            }},
            // {
            //     field: 'remark', title: '查看商品明细', width: 100, formatter: function (value, row, index) {
            //     return "<a href='#' id='detail' onclick='Showgoods();'>查看商品明细</a>";
            // }
            // }
        ]]
    })
    temporary_dialog.dialog({
        width: 1500,
        height: 800,
        buttons:'#form_btn',
        closed: true,
        //在窗口关闭的时候触发事件
        onClose: function () {
            //清空表单数据
            temporary_form.form('clear');
        }
    })
    import_dialog.dialog({
        width: 350,
        height: 100,
        closed: true
    })

    //会员
    choose_customer_dialog.dialog({
        width: 800,
        height: 350,
        buttons: '#customer_btns2',
        closed: true,
        modal: true
    });

    //2，将所有方法同一交给一个对象管理
    var methodObj = {
        edit: function () {
            var temporary = temporary_datagrid.datagrid("getSelected");
            if (!temporary) {
                $.messager.alert('温馨提示', '请选中一条记录！', 'info');
                return;
            }
            temporary_form.form("clear");
            temporary_dialog.dialog("setTitle", "保单编辑");
            temporary_dialog.dialog("open");
            console.log(temporary.id);
            $.get("/temporary/echo.do", {id: temporary.id}, function (data) {
                // 数据都封装到dialog上
                // 设置隐藏域

                console.log(data);

                //会员
                $("[name=id]").val(temporary.id);
                $("[name='customer.id']").val(data[0].customer.id);
                $("[name='customer.name']").val(data[0].customer.name);
                $("#customergender").combobox("setValue", data[0].customer.gender);
                $("[name='customer.tel']").val(data[0].customer.tel);
                $("[name='customer.idNo']").val(data[0].customer.idNo);
                $("#address").textbox("setValue", data[0].customer.address);

                // 设置车辆信息
                console.debug(data[0].car);

                $("#nnnnname").textbox("setValue",data[0].customer.name);
                $("#carbrand").textbox("setValue", data[0].car.brand);
                $("#carmodel").textbox("setValue", data[0].car.model);
                $("#carplateNumber").textbox("setValue",data[0].car.plateNumber);
                $("#fasDisplacement").textbox("setValue", data[0].car.fasDisplacement);
                $("#carcategory").combobox("setValue", data[0].car.category);
                $("#carvaluation").textbox("setValue", data[0].car.valuation);
                $("#carsize").combobox("setValue", data[0].car.size);


                // 设置保险产品
                var safe = "";
                $.each(data.products, function (index, item) {
                    safe = item.safetyMechanism;
                    var clone = $("#hidethis").clone(true);
                    clone.show();
                    clone.attr("data-oid", item.id);
                    clone.find("#productName").html(item.name);
                    clone.find("#productSn").html(item.sn);
                    clone.find("#annuaFlee").html(item.annuaFlee);
                    clone.insertAfter($("#hidethis"));
                });
                $("#safe_select").combogrid("setValue", safe.name);
                $("[name='duration']").val(data.duration);
                var totalAmout = 0;
                $.each($(".annuaFlee"), function (index, item) {
                    totalAmout = totalAmout + parseInt(item.innerHTML);
                })
                var duration = $("[name=duration]").val();
                $("#totalAmout").html(totalAmout * duration);

            });
        },

        select_product: function () {
            var products = product_datagrid.datagrid("getSelections");
            var oids = $.map($(".product-tr"), function (item, index) {
                return $(item).attr("data-oid");
            });
            $.each(products, function (index, item) {
                if ($.inArray(item.id + "", oids) == -1) {
                    var clone = $("#hidethis").clone(true);
                    clone.show();
                    clone.attr("data-oid", item.id);
                    clone.find("#productName").html(item.name);
                    clone.find("#productSn").html(item.sn);
                    clone.find("#annuaFlee").html(item.annuaFlee);
                    clone.insertAfter($("#hidethis"));
                }
            });
            var totalAmout = 0;
            $.each($(".annuaFlee"), function (index, item) {
                totalAmout = totalAmout + parseInt(item.innerHTML);
            })
            var duration = $("[name=duration]").val();
            $("#totalAmout").html(totalAmout * duration);
            choose_product_dialog.dialog("close");

        },
        add_product: function () {
            var safeId = $("#safe_select").combobox("getValue");
            if (safeId=="请选择" || safeId==null || safeId==''){
                $.messager.alert("温馨提示","亲, 请先选择承保机构!","warning");
                return;
            }
            choose_product_dialog.dialog("open");
            choose_product_dialog.dialog("setTitle","请选择保险产品");
            console.debug("safeId", safeId);
            $.get("/product/list.do",{smId:safeId,sStatus:1},function (data) {
                product_datagrid.datagrid("loadData", data);
            } );
            var clone = $("#hidethis").clone(true);

        },

        save: function () {
            $.messager.confirm("编辑", '编辑成功',  function (r){
                if(r){
                    temporary_dialog.dialog("close");
                }
            });

        },
        cancel: function () {
            temporary_dialog.dialog("close");
            $.each($(".product-tr"), function (index, item) {
                // console.debug($(item).attr("data-oid"));
                if ($(item).attr("data-oid")!=-1){
                    item.remove();
                }
            })
        },

        query: function () {
            var namekeyword = $("[name=namekeyword]").val();
            var snkeyword = $("[name=snkeyword]").val();
            temporary_datagrid.datagrid('load', {
                namekeyword: namekeyword,
                snkeyword:snkeyword,
            })
        },
        reload: function () {
            temporary_datagrid.datagrid("reload");
        },

        exportXls: function () {
            var keyword = $("[name=keyword]").val();
            var deptId = $("[name=deptId]").val();
            window.location.href = "/employee/exportXls.do?keyword=" + keyword + "&deptId=" + deptId;
        },
        importXls: function () {
            import_dialog.dialog('open');
        },
        drop:function(){
            var row = temporary_datagrid.datagrid('getSelected');
            if (!row) {
                $.messager.alert('温馨提示', '亲爱的,请选中数据', 'warning');
                return;
            }
            $.messager.confirm('确认对话框', '您确认要拒保吗？', function (r) {
                if (r) {
                    $.get('/temporary/drop.do', {id: row.id}, function (data) {
                        if (data.success) {
                            $.messager.alert('温馨提示', data.msg, 'info', function () {


                                temporary_datagrid.datagrid('reload');  //保持在当前页
                            });
                        } else {
                            $.messager.alert('温馨提示', data.msg, 'warning')
                        }
                    })
                }
            });
        },
        remand:function(){
            var row = temporary_datagrid.datagrid('getSelected');
            if (!row) {
                $.messager.alert('温馨提示', '亲爱的,请选中数据', 'warning');
                return;
            }
            $.messager.confirm('确认对话框', '请您再次确认,要提审吗？', function (r) {
                if (r) {
                    $.get('/temporary/remand.do', {id: row.id}, function (data) {
                        if (data.success) {
                            $.messager.alert('温馨提示', data.msg, 'info', function () {

                                temporary_datagrid.datagrid('reload');  //保持在当前页
                            });
                        } else {
                            $.messager.alert('温馨提示', data.msg, 'warning')
                        }
                    })
                }
            });
        },
        Showgoods:function () {
            console.log(55555555)
            var row = temporary_datagrid.datagrid('getSelected');
            if (!row) {
                $.messager.alert('温馨提示', '请选中数据', 'warning');
                return;
            }
            $.get('/temporary/selectByPrimaryKey.do', {id: row.product.id}, function (data) {
                product1_datagrid.datagrid("loadData", data);
                choose1_product_dialog.dialog("setTitle", "产品列表");
                choose1_product_dialog.dialog('open');

            })


        },
        choose_potentialCustomer: function(){

            choose_potentialCustomer_dialog.dialog("setTitle", "选择客户");

            choose_potentialCustomer_dialog.dialog("open")
        },

        choose_car: function(){
            choose_car_dialog.dialog("setTitle", "选择车辆");
            choose_car_dialog.dialog("open")
        },
        // 添加产品信息
        add_product: function () {
            var safeId = $("#safe_select").combobox("getValue");
            if (safeId=="请选择" || safeId==null || safeId==''){
                $.messager.alert("温馨提示","你没有选择任何机构","error");
                return;
            }
            choose_product_dialog.dialog("open");
            choose_product_dialog.dialog("setTitle","保险产品表");
            console.debug("safeId", safeId);
            var clone = $("#hidethis").clone(true);

        },
        select_potentialCustomer: function () {
            sure_potentialCustomer();
        },
        select_car: function () {
            sure_car();
        },
        // 选中的保险产品信息添加到页面
        select_product: function () {
            var products = product_datagrid.datagrid("getSelections");
            var oids = $.map($(".product-tr"), function (item,index) {
                return $(item).attr("data-oid");
            });

            $.each(products, function (index, item) {
                if ($.inArray(item.id + "", oids)==-1){
                    var clone = $("#hidethis").clone(true);
                    clone.show();
                    clone.attr("data-oid",item.id);
                    clone.find("#productName").html(item.name);
                    clone.find("#productSn").html(item.sn);
                    clone.find("#annuaFlee").html(item.annuity);
                    clone.insertAfter($("#hidethis"));
                }
            });
            var totalAmout = 0;
            $.each($(".annuaFlee"), function (index, item) {
                totalAmout = totalAmout + parseInt(item.innerHTML);
            })
            var duration = $("[name=duration]").val();
            console.log(totalAmout * duration);
            $("#totalAmout").html(totalAmout * duration);
            choose_product_dialog.dialog("close");
        }

    }




    //3，给按钮统一绑定点击事件
    $("a[data-cmd]").click(function () {
        //获取按钮上的data-cmd的值
        var methodName = $(this).data("cmd");
        methodObj[methodName]();
    })
})

function calculate() {
    var totalAmout = 0;
    $.each($(".annuaFlee"), function (index, item) {
        totalAmout = totalAmout + parseInt(item.innerHTML);
    })
    var duration = $("[name=duration]").val();
    console.log(totalAmout * duration);
    $("#totalAmout").html(totalAmout * duration);
    choose_product_dialog.dialog("close");
}


function sure_potentialCustomer() {
    var potentialCustomer = $("#potentialCustomer_datagrid").datagrid("getSelected");
    $("[name='customer.id']").val(potentialCustomer.id);
    $("[name='customer.idNo']").val(potentialCustomer.idNo);
    $("[name='customer.tel']").val(potentialCustomer.tel);
    $("#address").textbox("setValue", potentialCustomer.address);
    $("[name='customer.name']").val(potentialCustomer.name);
    $("#customergender").combobox("setValue",potentialCustomer.gender);
    $("#choose_potentialCustomer_dialog").dialog("close");
}
function sure_car() {
    var car = $("#car_datagrid").datagrid("getSelected");

    $("#carbrand").textbox("setValue", car.brand);
    $("#carmodel").textbox("setValue",car.model);
    $("#fasDisplacement").textbox("setValue",car.fasDisplacement);
    $("#carcategory").combobox("setValue",car.category);
    $("#carsize").combobox("setValue",car.size);
    $("#carvaluation").textbox("setValue",car.valuation);


    $("#choose_car_dialog").dialog("close");
}



function fileSubmit() {
    var fileSize = $("#file").val();
    if(fileSize!=null && fileSize != ''){
        console.log("bu");
        $("#import_form").submit();
    }else {
        $.messager.alert('温馨提示', '请选中要上传的文件！', 'warning');
    }
}

// 暂存保单, 提交表单
function temporary_submit() {
    $("#form").form("submit", {
        url: '/temporary/saveOrUpdate.do',
        onSubmit: function (param) {
            var oids = $.map($(".product-tr"), function (item,index) {
                return $(item).attr("data-oid");
            });
            // shift() 方法用于把数组的第一个元素从其中删除，并返回第一个元素的值。
            oids.shift();
            param.pIds = oids;
            // console.debug($("#totalAmout").html());
            // param.totalAmout = $("#totalAmout").html();
        },
        success: function (data) {
            data = $.parseJSON(data)
            if (data.success) {
                $.messager.alert('温馨提示', '保存成功', 'info', function () {
                    $("#form").form('clear');
                    $("#temporary_dialog").dialog("close");
                })
            } else {
                $.messager.alert('温馨提示', data.msg, 'error')
            }
        }
    });
}
function Showgoods() {

    $.messager.alert("对不起", '服务器繁忙,请点击菜单栏的通道', "info");
}
